package site.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import neoutil.Config;

import site.entity.Role;
import site.entity.User;

import com.rain.acm.Sso;

public class loginFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		System.out
				.println("==================================loginFiler=================================");
		System.out.println("loginFiler\tSso.hasLogin()::::" + Sso.hasLogin());
		if (Sso.hasLogin()) {
			Map<String, Object> userInfo = new HashMap<String, Object>();
			userInfo = Sso.myInfo();
			String userName = userInfo.get("username").toString();
			String email = userInfo.get("email").toString();
			String realName = userInfo.get("realname").toString();

			System.out.println(userName + "\t" + email + "\t" + realName);

			System.out.println(userInfo.size());

			System.out.println(userInfo.toString());

			Object[] keys = new Object[userInfo.size()];

			keys = userInfo.keySet().toArray();

			for (int i = 0; i < keys.length; i++) {
				System.out.println(keys[i].toString() + "=========="
						+ userInfo.get(keys[i]));
			}
		}
		HttpServletRequest req = (HttpServletRequest) request;
		User user = (User) req.getSession().getAttribute("loginUser");
		if (user == null) {
			System.out.println("用户尚未登录，需要重新登录！");
			((HttpServletResponse) response)
					.sendRedirect("../relogin.action?redirect="
							+ req.getRequestURI()
							+ (req.getQueryString() == null ? "" : "?"
									+ req.getQueryString()));
		} 
		else if(user!=null && user.getRid() == Role.GUSET)
		{
			if(req.getRequestURI().contains("AddResource"))
			{
				chain.doFilter(request, response);			
			}
			else
			{
				System.out.println("用户权限不足！");
				((HttpServletResponse) response)
						.sendRedirect(Config.getHostURL());
			}
		}
		else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
